package com.sentiment.servlet;

import java.io.IOException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.bson.Document;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.sentiment.bean.OperationInfo;
import com.sentiment.database.bean.Permission;
import com.sentiment.database.bean.User;
import com.sentiment.database.bean.UserLog;
import com.sentiment.database.dbUtil.DbUtil;
import com.sentiment.shiro.ActiveUser;
import com.sentiment.tools.Format;
import com.sentiment.tools.Paging;

/**
 * Servlet implementation class LogInfoServlet
 */
@WebServlet("/LogInfoServlet")
public class LogInfoServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
   
	protected void doGet(HttpServletRequest request, HttpServletResponse response) 
			throws ServletException, IOException {
		doPost(request, response);
	}

	
	protected void doPost(HttpServletRequest request, HttpServletResponse response) 
			throws ServletException, IOException {
		
		String methodName = request.getParameter("method");
		try{
			Method method = getClass().getMethod(methodName, 
					HttpServletRequest.class, HttpServletResponse.class);
			method.invoke(this, request, response);
		}catch(Exception e){
			e.printStackTrace();
		}
	}

	
	/**
	 * 获取所有操作日志信息
	 * @param request
	 * @param response
	 * @throws ServletException
	 * @throws IOException
	 */
	public void GetLogInfoList(HttpServletRequest request, HttpServletResponse response) 
			throws ServletException, IOException {
		
		int page  = Integer.parseInt(request.getParameter("pagenum"));
		List<Document> tlist = new ArrayList<>();
		DbUtil db = new DbUtil();
		db.openConnection(UserLog.dbName, UserLog.collection);
		tlist = db.getPage(page, 10);
		long count = db.collectionGetCount();
		db.closeConnection();
		
		List<UserLog> userloglist = new ArrayList<>();
		UserLog userlog = new UserLog();
		for (int i = 0; i < tlist.size(); i++) {
			userlog = new UserLog(tlist.get(i));
			userloglist.add(userlog);
		}
		
		String usercode = "";
		boolean status = false;
		Subject subject = SecurityUtils.getSubject();
		ActiveUser activeUser = (ActiveUser) subject.getPrincipal();
		if(activeUser != null){
			usercode = activeUser.getUsercode();
			List<String> role = activeUser.getRole();
			if(role.contains("admin")){
				status = true;
			}
		}
		
		ObjectMapper mapper = new ObjectMapper();
		String jsonArr = mapper.writeValueAsString(userloglist);
		String jsonStr = "{\"recordsTotal\":"+ count +",\"LogInfo\":" + jsonArr + ",\"usercode\":" + "\"" +usercode + "\"" + ",\"status\":" + status +"}";
		System.out.println(jsonStr);
		response.setCharacterEncoding("UTF-8");
		response.getWriter().print(jsonStr);
	}
	
	/**
	 * 获取单个用户操作日志信息
	 * @param request
	 * @param response
	 * @throws ServletException
	 * @throws IOException
	 */
	public void GetUserLogInfoList(HttpServletRequest request, HttpServletResponse response) 
			throws ServletException, IOException {
		
		String user_id = request.getParameter("user_id");
		int page  = Integer.parseInt(request.getParameter("pagenum"));
		
		if(user_id.equals("myself")){
			Subject subject = SecurityUtils.getSubject();
			ActiveUser activeUser = (ActiveUser) subject.getPrincipal();
			if(activeUser == null){
				user_id = null;
			}else{
				user_id = activeUser.getUser_id();
			}
		}
		String jsonStr = "";
		if(user_id == null){
			jsonStr = "{\"Info\":" + "\"" + OperationInfo.LoginTimeOut + "\"" +"}";
		}else{
			DbUtil db = new DbUtil();
			db.openConnection(UserLog.dbName, UserLog.collection);
			
			UserLog log = new UserLog(user_id, null, null, null);
			String []keys = {"user_id"};
			List<Document> tlist = db.queryMany(log.toDocument(), keys);
			db.closeConnection();
			
			long count= tlist.size();
			tlist = Paging.paging(tlist, page, 10);
			List<UserLog> userloglist = new ArrayList<>();
			for (int i = 0; i < tlist.size(); i++) {
				log = new UserLog(tlist.get(i));
				userloglist.add(log);
			}
			
			ObjectMapper mapper = new ObjectMapper();
			String jsonArr = mapper.writeValueAsString(userloglist);
			jsonStr = "{\"recordsTotal\":"+ count +",\"LogInfo\":" + jsonArr+"}";
		}
		System.out.println(jsonStr);
		response.setCharacterEncoding("UTF-8");
		response.getWriter().print(jsonStr);
	}
	
	/**
	 * 查询操作日志 可输入 用户名、操作时间、操作类型、ip 地址 ，进行查询 
	 * @param request
	 * @param response
	 * @throws ServletException
	 * @throws IOException
	 */
	public void Query(HttpServletRequest request, HttpServletResponse response) 
			throws ServletException, IOException {	
		request.setCharacterEncoding("UTF-8");
		String usercode = request.getParameter("usercode");
		String operationdate = request.getParameter("operationdate");
		String operation = request.getParameter("operation");
		String ipadd = request.getParameter("ipadd");
		int page  = Integer.parseInt(request.getParameter("pagenum"));		
		
		List<String> keylist = new ArrayList<>();
		String user_id = "";
		String info = "";
		if(!usercode.equals("")){
			User user = new User();
			user = user.getUserByUserCode(usercode);
			if(user == null){
				info = OperationInfo.NoSuchUserLog;
			}else{
				user_id = user.get_id();
				keylist.add("user_id");
			}
		}
		if(!operationdate.equals("")){
			operationdate = Format.ToDBStrDate(operationdate);
			keylist.add("operationdate");
		}
		if(!operation.equals("")){
			keylist.add("operation");
		}
		if(!ipadd.equals("")){
			keylist.add("ipadd");
		}
		
		
		long count = 0;
		String jsonArr = "";
		if(info.equals("") && keylist.size() != 0){
			UserLog userlog = new UserLog(user_id, operationdate, operation, ipadd);
			String []keys = keylist.toArray(new String [keylist.size()]);
			
			DbUtil db = new DbUtil();
			db.openConnection(UserLog.dbName, UserLog.collection);
			List<Document> tlist = new ArrayList<>();
			tlist =	db.queryMany(userlog.toDocument(), keys);
			db.closeConnection();
			count = tlist.size();
			
			if(count != 0){
				tlist = Paging.paging(tlist, page, 10);
				List<UserLog> userloglist = new ArrayList<>();
				for (int i = 0; i < tlist.size(); i++) {
					userlog = new UserLog(tlist.get(i));
					userloglist.add(userlog);
				}
				
				ObjectMapper mapper = new ObjectMapper();
				jsonArr = mapper.writeValueAsString(userloglist);
			}else{
				info = OperationInfo.NoSuchUserLog;
			}
			
		}else{
			info = OperationInfo.NoSuchUserLog;
		}

		String jsonStr = "";
		if(info.equals("")){
			
			jsonStr = "{\"recordsTotal\":"+ count +",\"LogInfo\":" + jsonArr+"}";
		}else{
			jsonStr = "{\"recordsTotal\":"+ count +",\"Info\":" + "\"" + info + "\"" +"}";
		}
		System.out.println(jsonStr);
		response.setCharacterEncoding("UTF-8");
		response.getWriter().print(jsonStr);
	}
	
}
